package com.shrw.duke.serialport.port.p;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.pda.serialport.SerialPort;


/**
 * 汉德霍尔手持机端口操作
 *
 * @author: ZengZhenHua
 * @date: 2018/12/20
 * @email: cengzhenghua@163.com
 */
public class HanDePort extends Port {
    private SerialPort mPort = null;
    private boolean isScan;

    @Override
    public void initPort() {
        if (mPort == null) {
            mPort = new SerialPort();
        }
    }

    @Override
    public boolean isOpen() {
        return mPort == null ? false : isScan;
    }

    @Override
    public FileDescriptor open() throws SecurityException, IOException {
        if (!isScan) {
            mPort.open(13, 115200, 0);
            mPort.power3v3on();
            mPort.rfid_poweron();
            isScan = true;
        }
        return mPort.getFileDescriptor();
    }

    @Override
    public void close() {
        if (isScan){
            mPort.rfid_poweroff();
            mPort.power3v3off();
            isScan = false;
        }
    }

    @Override
    public FileInputStream getFileInputStream(FileDescriptor fd) {
        return mPort == null ? null : new FileInputStream(mPort.getFileDescriptor());
    }

    @Override
    public FileOutputStream getFileOutputStream(FileDescriptor fd) {
        return mPort == null ? null : new FileOutputStream(mPort.getFileDescriptor());
    }

    @Override
    public void destroy() {
        close();
        mPort = null;
    }
}
